<?php

namespace app\models;

use common\core\ZActiveRecord;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%zs_users}}".
 *
 * @property integer $user_id
 * @property string $real_name
 * @property string $user_pwd
 * @property integer $create_time
 * @property integer $update_time
 * @property string $user_email
 * @property integer $user_sex
 * @property string $user_img
 * @property integer $is_valid
 */
class Users extends ZActiveRecord implements IdentityInterface
{
    private $auth_key;
    const STATUS_DELETED = -1;
    const STATUS_ACTIVE = 1;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%zs_users}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['create_time','update_time'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time']
                ],
            ],


        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['create_time', 'update_time', 'user_sex', 'is_valid'], 'integer'],
            [['user_email','real_name','user_pwd','user_sex'], 'required'],
            [['user_email'], 'email'],
            [['real_name', 'user_pwd', 'user_email', 'user_img'], 'string', 'max' => 255],
//            [['user_img'] ,'file' ,'skipOnEmpty' => false , 'extensions' => 'png , jpg'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'user_id' => '用户ID',
            'real_name' => '用户名称',
            'user_pwd' => '密码',
            'create_time' => '创建时间',
            'update_time' => '最后更新时间',
            'user_email' => '邮箱',
            'user_sex' => '性别',
            'user_img' => '用户头像',
            'is_valid' => '是否有效 -1无效，1有效',
        ];
    }

    function beforeSave($insert = true)
    {
        parent::beforeSave($this->isNewRecord);
        $this->generateAuthKey();
        //保存之前先把密码进行hash加密
        $this->user_pwd = Yii::$app->security->generatePasswordHash($this->user_pwd);
        if($this->isNewRecord){
            $this->create_time = time();
        }
        $this->update_time = time();
        return true;
    }



    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['user_id' => $id, 'is_valid' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     *  用户名的字段已经改为real_name 为了继承接口必须写此方法。但一样可用。
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['real_name' => $username, 'is_valid' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by real_name
     *
     * @param string $username
     * @return static|null
     */
    public static function findByRealname($username)
    {
        return static::findOne(['real_name' => $username, 'is_valid' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->user_pwd);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->user_pwd = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

//    public static function

    /**
     * @inheritdoc
     * @return UsersQuery the active query used by this AR class.
     */
//    public static function find()
//    {
//        return new UsersQuery(get_called_class());
//    }

//    public function behaviors()
//    {
//        return array(
//            'class' => TimestampBehavior::className(),
//            'attributes' => [
//                ActiveRecord::EVENT_BEFORE_INSERT => ['create_time' , 'update_time'],
//                ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
//            ]
//        );
//    }

}
